﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Studio.InfoPlus.BusinessServices.Entities;
using Studio.Foundation.Json.Core.Conversion;
using Studio.Foundation.Json;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Schema;

public partial class JsonConvert_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        FormEntity entity = new FormEntity();
        Studio.InfoPlus.BusinessServices.Entities.FormView view = new Studio.InfoPlus.BusinessServices.Entities.FormView();
        RenderAttribute a1 = new RenderAttribute("name", "111");
        RenderAttribute a2 = new RenderAttribute("name", "222");
        RenderAttribute a3 = new RenderAttribute("name", "333");
        RenderAttribute a4 = new RenderAttribute("name", "444");
        RenderAttribute a5 = new RenderAttribute("name", "555");

        view.Attributes.Add(a1);
        view.Attributes.Add(a2);

        LayoutDivision div = new LayoutDivision();
        div.Attributes.Add(a3);
        div.Attributes.Add(a4);
        //view.AddRenderable(div);
        entity.Views.Add(view);

        string s = JsonConvert.ExportToString(entity);

        Response.Write(s);
    }


    protected void Button2_Click(object sender, EventArgs ex)
    {

        // Studio.InfoPlus.BusinessServices.Entities.FormView view = new Studio.InfoPlus.BusinessServices.Entities.FormView();
        // string s = JsonConvert.ExportToString(view);
        //  Response.Write(s);
        string s = @"<entry xmlns=""http://sjtu.edu.cn/WorkflowService"">
            <key xsi:type=""xsd:string"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">id</key>
            <value xsi:type=""xsd:string"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">field5</value>
        </entry>
        <entry xmlns=""http://sjtu.edu.cn/WorkflowService"">
            <key xsi:type=""xsd:string"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">permission</key>
            <value xsi:type=""xsd:string"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">rw</value>
        </entry>";

        s = @"<entry>
            <key>id</key>
            <value>field5</value>
        </entry>
        <entry xmlns=""http://sjtu.edu.cn/WorkflowService"">
            <key>permission</key>
            <value xsi:type=""xsd:string"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">rw</value>
        </entry>";

        string ns = "http://sjtu.edu.cn/WorkflowService";
        XDocument doc = XDocument.Parse("<root>" + s + "</root>");
        var x = doc.Root.Elements("{" + ns + "}entry").First();

        string xpath = "//*[local-name()='value' and (../*[local-name()='key' and contains(text(), '{0}')])]/text()";


        var y = ((IEnumerable<object>)doc.XPathEvaluate(string.Format(xpath, "id"))).FirstOrDefault().ToString();

        string id = (from e in doc.Root.Elements("entry")
                   where e.Element("key").Value == "id"
                   select e.Element("value").Value).FirstOrDefault();
        string pe = (from e in doc.Root.Elements("entry")
                           where e.Element("key").Value == "permission"
                           select e.Element("value").Value).FirstOrDefault();

    }


    protected void Button3_Click(object sender, EventArgs e)
    {
        string data = "{\"my:field1\":\"Field1_Data\",\"my:field4\":[\"Field5_R1_Data\",\"Field5_R2_Data\",\"\"],\"my:field5\":[true,false,true],\"my:field9\":[\"\"],\"my:field10\":[\"\"],\"my:field11\":[\"\"]}";
        data = "[{\"key\":\"success\",\"value\":true}]";
        object o = JsonConvert.Import<Dictionary<string, object>>(data);
        Dictionary<string, object> formData = o as Dictionary<string, object>;
        string s = JsonConvert.ExportToString(formData);
        Response.Write(s);
    }

    protected void ButtonWS_Click(object sender, EventArgs e)
    {
        long t = UnixTime.ToInt64(DateTime.Now);
        Response.Write(t);


        DateTime unixRef = new DateTime(1970, 1, 1, 0, 0, 0);
        
        DateTime t2 = unixRef.AddSeconds(t);
        DateTime t1 = UnixTime.ToDateTime(t);
        Response.Write("<br/>" + t1);
        Response.Write("<br/>" + t2.ToLocalTime());


    }

    /// <summary>
    /// Common invoke Workflow WebService method & returns Json serialized HashMap
    /// </summary>
    static string InvokeMethodJson(string method, params object[] arguments)
    {
        string url = "http://202.120.58.52/workflow/services/WorkflowService?wsdl";
        object[] args = new object[arguments.Length];
        for (int i = 0; i < arguments.Length; i++) args[i] = arguments[i];
        object result = Studio.Web.Utilities.WebServiceHelper.InvokeWebService(url, method, args);
        IDictionary<string, object> dict = new Dictionary<string, object>();
        

        return JsonConvert.ExportToString(result);
    }

    static IDictionary<string, object> InvokeMethod(string method, params object[] arguments)
    {
        string url = "http://202.120.58.52/workflow/services/WorkflowService?wsdl";
        object[] args = new object[arguments.Length];
        for (int i = 0; i < arguments.Length; i++) args[i] = arguments[i];
        object result = Studio.Web.Utilities.WebServiceHelper.InvokeWebService(url, method, args);
        object[] results = (result as object[]);
        IDictionary<string, object> dict = new Dictionary<string, object>();
        string keyMethod = "key";
        string valMethod = "value";
        if (null != results)
        {
            foreach (object r in results)
            {
                string key = (string)r.GetType().InvokeMember(keyMethod,
                    System.Reflection.BindingFlags.GetField |
                    System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.Instance,
                    null, r, null);

                object val = r.GetType().InvokeMember(valMethod,
                    System.Reflection.BindingFlags.GetField |
                    System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.Instance,
                    null, r, null);

                if (typeof(XmlNode[]) == val.GetType())
                {
                    IList<string> xmlList = new List<string>();
                    foreach (XmlNode node in (val as XmlNode[]))
                        if (node is XmlElement)
                            xmlList.Add((node as XmlElement).InnerXml);
                    dict.Add(key, xmlList);
                }
                else
                {
                    dict.Add(key, val);
                }
            }
        }
        return dict;
    }

    protected void ButtonResponseEntity_Click(object sender, EventArgs e)
    {
        string data = "{\"errno\":0,\"error\":\"Succeed.\",\"entities\":[\"s1\", \"s2\"],\"total\":0}";
        data = ReadFile("C:\\Users\\marstone\\Desktop\\SJTU-NIC\\SJTURight\\property.txt");

        // ResponseEntity<string> o = JsonConvert.Import<ResponseEntity<string>>(data);
        ResponseEntity<SJTU.SJTURight.Entities.EntitleRightProperty> o = 
            JsonConvert.Import<ResponseEntity<SJTU.SJTURight.Entities.EntitleRightProperty>>(data);
        string s = JsonConvert.ExportToString(o);
        Response.Write(s);
    }


    string ReadFile(string path)
    {
        // FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(path);
        return reader.ReadToEnd();
    }
    

}